<template>
  <Card :bordered="false">
    <p slot="title">
      <Icon type="logo-codepen"></Icon>
      应用发布
    </p>
    <a href="#" v-if="permission.deploy_create === '1'" slot="extra" @click.prevent="createModal=true">
      <Icon type="md-add-circle"></Icon>
      创建
    </a>
    <Modal v-model="createModal" draggable scrollable title="新建项目" :footer-hide=true width="900">
      <Form ref="formCreate" :model="formCreate" :rules="ruleCreate" :label-width="100" inline>
        <FormItem label="项目名称" prop="name">
          <Input v-model="formCreate.name" style="width:300px" placeholder="服务名称"></Input>
        </FormItem>
        <FormItem label="所属环境" prop="env">
          <Select v-model="formCreate.env" style="width:300px">
            <Option v-for="item in env_names" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="项目端口" prop="port">
          <Input v-model="formCreate.port" style="width:300px" placeholder="服务端口"></Input>
        </FormItem>
        <FormItem label="语言类型" prop="application_type">
          <Select v-model="formCreate.application_type" style="width:300px">
            <Option v-for="item in language_types" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="代码地址(ssh)" prop="git_repo">
          <Input v-model="formCreate.git_repo" style="width:300px" placeholder="ssh://git@xxx.git"></Input>
        </FormItem>
        <FormItem label="代码分支" prop="branch">
          <Input v-model="formCreate.branch" style="width:300px" placeholder="代码分支"></Input>
        </FormItem>
        <FormItem label="主机记录" prop="domain">
          <Input v-model="formCreate.domain" style="width:300px" placeholder="用于DNS的A记录主机名"></Input>
        </FormItem>
        <FormItem label="动态参数" prop="params">
          <Input v-model="formCreate.params" style="width:300px" type="textarea" placeholder="构建传参，以逗号隔开，如：param1,param2"></Input>
        </FormItem>
        <!-- <FormItem style="width:100%"> -->
        <div style="margin-left:35%">
          <Button type="success" @click="createDeploy_info('formCreate')">点击提交</Button>
          <Button type="warning" @click="handleReset('formCreate')" style="margin-left: 8px">清空</Button>
          <Button type="info" @click="createModal=false" style="margin-left: 8px">关闭</Button>
        </div>
        <!-- </FormItem> -->
      </Form>
    </Modal>
    <Tabs type="card" v-model="tabs_value" @on-click="tabsChange">
      <TabPane v-for="(env,index) in env_names" :key="index" :label="env.label" :name="env.value">
        <div style="padding-bottom: 10px;">
          <Row>
            <Col span="6">
              <!-- <Cascader :data="language_types"  @on-change=data_list trigger="hover"></Cascader> -->
              <Select v-model="appType"  placeholder="请选择语言类型" @on-change="data_list">
                <Option v-for="item in language_types" :value="item.value" :key="item.value">{{ item.value }}</Option>
              </Select>
            </Col>
            <Col span="6" offset="12">
              <Input search placeholder="Search ..." v-model="searchValue" @on-search=searchDeploy />
            </Col>
          </Row>
        </div>
        <div>
          <Table :border=false :columns="columns1" :data="data1">
            <template slot-scope="{ row, index }" slot="status">
              <span style="color:#ed4014" v-if="`${ row.status }`=='failed'"><Icon size="15" type="md-rainy" />构建失败</span>
              <span style="color:#ff9900" v-if="`${ row.status }`=='building'"><Icon size="15" type="ios-thunderstorm" />正在构建</span>
              <span style="color:#19be6b" v-if="`${ row.status }`=='success'"><Icon size="15" type="md-sunny" />构建成功</span>
              <span style="color:#2db7f5" v-if="`${ row.status }`=='unknown'"><Icon size="15" type="md-cloudy" />新项目</span>
            </template>
            <template slot-scope="{ row, index }" slot="action">
              <Button type="primary" size="small" style="margin-right: 5px" @click="deployView(index)">查看</Button>
              <Button v-if="permission.deploy_build === '1'" type="success" size="small" style="margin-right: 5px" :loading="row.status==='building' " @click="deployOpration(index, 'deploy')">
                <span v-if="row.status==='building'">构建中...</span>
                <span v-else>构建</span>
              </Button>
              <Button type="info" size="small" style="margin-right: 5px" @click="logView(index, 'logs')">日志</Button>
              <Button v-if="permission.deploy_update === '1'" type="warning" size="small" style="margin-right: 5px" @click="updateDeploy_id(index)">修改</Button>
              <Button v-if="permission.deploy_delete === '1'" type="error" size="small" @click="remove(index)">删除</Button>
            </template>
          </Table>
          <div style="padding-top: 10px;" v-if="count">
            <template>
              <Page :total="count" show-total :page-size-opts="[10,25,40,55,70,100]" current.sync="current" show-elevator show-sizer @on-change="switchPage" @on-page-size-change="switchPageSize" />
            </template>
          </div>
        </div>
      </TabPane>
    </Tabs>
    <Modal v-model="updateModal" draggable scrollable :title="update_title" @on-ok="updateDeploy_info" width="900">
      <Form id="abc" ref="formUpdate" :model="formUpdate" :label-width="100" inline>
        <FormItem label="项目名称" prop="name">
          <Input v-model="formUpdate.name" placeholder="Enter your project name" style="width:300px"></Input>
        </FormItem>
        <FormItem label="所属环境" prop="env">
          <Select v-model="formUpdate.env" style="width:300px">
            <Option v-for="item in env_names" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="项目端口" prop="port">
          <Input v-model="formUpdate.port" placeholder="Enter your port" style="width:300px"></Input>
        </FormItem>
        <FormItem label="语言类型" prop="application_type">
          <Select v-model="formUpdate.application_type" style="width:300px">
            <Option v-for="item in language_types" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="代码地址(ssh)" prop="git_repo">
          <Input v-model="formUpdate.git_repo" placeholder="Enter your git_repo" style="width:300px"></Input>
        </FormItem>
        <FormItem label="代码分支" prop="branch">
          <Input v-model="formUpdate.branch" placeholder="Enter your git branch" style="width:300px"></Input>
        </FormItem>
        <FormItem label="主机记录" prop="domain">
          <Input v-model="formUpdate.domain" placeholder="Enter your domain" style="width:300px"></Input>
        </FormItem>
        <FormItem label="动态参数" prop="params">
        <Input v-model="formUpdate.params" style="width:300px" type="textarea" placeholder="构建传参，以逗号隔开，如：param1,param2"></Input>
      </FormItem>
      </Form>
    </Modal>
    <Modal v-model="logModal" draggable scrollable :width="800">
      <p slot="header" style="color:#17233d;text-align:center">
        <span>{{logView_title}}</span>
      </p>
      <div style="padding: 0px 40px 20px;  height:650px; overflow-y: scroll; color:#17233d;">
        <ol reversed style="list-style:none">
          <li v-for="(log,index) in log_data" :key="index">
            {{ log }}
          </li>
        </ol>
      </div>
      <!-- 自定义页脚按键 -->
      <div slot="footer">
        <Button type="dashed" style="margin-right: 5px" @click="closeLogView">关闭</Button>
      </div>
      <!-- 自定义页眉按键 -->
      <div slot="close">
        <!-- <a href="#" slot="extra" @click.prevent="closeLogView"> -->
          <!-- <Icon type="md-close"> </Icon> -->
        <!-- </a> -->
      </div>
    </Modal>
  </Card>
</template>

<script>
import { addDeploy, deployList, updateDeploy, deleteDeploy, deployBuildOrLogs, deployAllSearch } from '@/api/deploy'
import { deployConfTypeDetail, deployConfEnvsDetail } from '@/api/deploy'

  export default {
    data () {
      return {
        updateModal: false,
        createModal: false,
        logModal: false,
        search_value: '',
        update_title: '',
        logView_title: '',
        searchValue: '',
        count: null,
        env: '',
        tabs_value: 'test',
        appType: '',
        page: 1,  //设置默认页码为1
        pageSize: 10, //设置每页总条数默认为10条
        selec_env_men: [],
        data1: [],
        env_names: [],
        language_types: [],
        log_data: [],
        formCreate: {
          name: '',
          env: '',
          // env_label: '',
          port: '',
          application_type: '',
          git_repo: '',
          branch: 'master',
          domain: '',
          params: ''
        },
        formUpdate: {
          name: '',
          env: '',
          // env_label: '',
          port: '',
          application_type: '',
          git_repo: '',
          branch: '',
          domain: '',
          params: ''
        },
        ruleCreate: {
          name: [
            { required: true, message: 'The name cannot be empty', trigger: 'blur' }
          ],
          env: [
            { required: true, message: 'The env env be empty', trigger: 'blur' }
          ],
          port: [
            { required: true, message: 'The port cannot be empty', trigger: 'blur' }
          ],
          application_type: [
            { required: true, message: 'The application_type cannot be empty', trigger: 'blur' }
          ],
          git_repo: [
            { required: true, message: 'The git_repo cannot be empty', trigger: 'blur' }
          ],
          branch: [
            { required: true, message: 'The git branch cannot be empty', trigger: 'blur' }
          ]
        },
        columns1: [
          {
            title: '名称',
            key: 'name'
          },
          {
            title: '环境',
            key: 'env'
          },
          {
            title: '语言类型',
            key: 'application_type'
          },
          {
            title: '分支',
            key: 'branch'
          },
          {
            title: '端口',
            key: 'port'
          },
          {
            title: '运行状态',
            key: 'status',
            slot: 'status'
          },
          {
            title: '创建日期',
            key: 'create_time'
          },
          {
            title: '更新日期',
            key: 'update_time'
          },
          {
            title: '操作',
            slot: 'action',
            width: 300,
            align: 'center'
          }
        ],
        permission: ''
      }
    },
    mounted () {
      this.mens()
    },
    created () {
      this.get_permission()
    },
    methods: {
      tabsChange(){
        console.log("清空")
        this.appType = '';
        this.data1= [];
        this.searchValue = '';
        this.page = 1;
        this.pageSize = 10;
      },
      // 获取用户操作权限
      get_permission () {
        const auth = JSON.parse(sessionStorage.getItem('permission'))
        this.permission = auth.child;
      },
      // 应用发布菜单
      mens () {
        // 获取所有环境
        var envs = JSON.parse(sessionStorage.getItem('permission')).child.deploy_env;
        deployConfEnvsDetail().then(res => {
          var envs_data = res.data.results
          for (var line in envs) {
            for (var service_type in envs_data) {
              if (envs_data[service_type].name === envs[line]) {
                this.env_names.push({'value':envs_data[service_type].name,'label':envs_data[service_type].label})
              }
            }
          }
        })
        // 获取所有开发语言类
        deployConfTypeDetail().then(res => {
          var types_data = res.data.results
          for (var language_type in types_data) {
            this.language_types.push({'value':types_data[language_type].name,'label':types_data[language_type].name})
          }
        })
      },
      // 执行项目发布
      deployOpration(index, val) {
        const project_id = this.data1[index].id
        const params = {
          'oprate_param': val
        }
        this.$Notice.info({title:'提交请求,请稍候...'});
        deployBuildOrLogs(project_id,params).then(res => {
          if (res.data.code === 200) {
            this.$Notice.success({title: `项目【${this.data1[index].name}】 构建成功！`});
          } else {
            this.$Notice.error({title: `项目【${this.data1[index].name}】 构建失败！`});
          }
        }).catch(err => {
          this.$Notice.error({title: `项目【${this.data1[index].name}】 构建失败！`});
        })
        //   var new_loading_deploy_false = [...this.loading_deploy]   //复制一loading_deploy份数组
      },
      // 获取实时发布日志
      logView (index,val) {
        if (this.logModal === true) {
          this.$Message.warning({content:'不能同时打开2个及以上日志显示窗口!',duration: 5,closable: true})
        } else {
          const project_id = this.data1[index].id
          const params = {
            'oprate_param': val
          }
          deployBuildOrLogs(project_id,params).then(res => {
            this.logModal = true  // 拿到日志再弹出日志显示窗口
            this.logView_title = this.data1[index].name   //拿到日志再个性窗口标题
            this.log_data = res.data.results
            // 定时获取日志
            this.inter = setInterval(() =>
              deployBuildOrLogs(project_id,params).then(res => {
                this.$nextTick(() => {
                  this.log_data = res.data.results
                })
              }),
              2000
            )
          }).catch(err => {
            this.$Notice.error({title: `项目【${this.data1[index].name}】 无法获取日志！`});
          })
        }
      },
      // 关闭日志窗口
      closeLogView () {
        this.logModal = false;
        clearInterval(this.inter);  //关闭日志获取定时任务
      },
      // 获取项目数据
      data_list (data) {
        this.env = this.tabs_value
        if(this.appType){
          deployList(this.env, this.appType, 1, 10, this.searchValue).then(res => {
            res.data.results.forEach(element => {
              for (var envs in this.env_names) {
                if ( this.env_names[envs]['value'] === element['env']) {
                  element['env'] = this.env_names[envs]['label']
                }
              }
            });
            this.data1 = res.data.results
            this.count = res.data.count
          })
        }
      },
      // 创建新项目
      createDeploy_info (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            // 请求后端接口创建数据
            addDeploy(this.formCreate).then(res => {
              // 在创建新地址时再次请求数据
              deployList(this.env, this.appType, this.page, this.pageSize, this.searchValue).then(res => {
                res.data.results.forEach(element => {
                  for (var envs in this.env_names) {
                    if ( this.env_names[envs]['value'] === element['env']) {
                      element['env'] = this.env_names[envs]['label']
                    }
                  }
                });
                this.data1 = res.data.results
                this.count = res.data.count
              })
              this.$Message.success({content:'创建成功!',duration: 5,closable: true});
            }).catch( err => {
              this.$Message.error({content:'创建失败!',duration: 5,closable: true})
            })
          }
        })
      },
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      // 获取id,获取应用名称并赋值
      updateDeploy_id (index) {
        this.updateModal = true
        this.columns_id = this.data1[index].id
        this.update_title = `更新${this.data1[index].name}`
        this.formUpdate = this.data1[index]
        for (var envs in this.env_names) {
          if (this.formUpdate['env']==this.env_names[envs]['label']) {
            this.formUpdate['env'] = this.env_names[envs]['value']
          }
        };
      },
      // 更新项目信息
      updateDeploy_info () {
        updateDeploy(this.columns_id, this.formUpdate).then(res => {
          this.$Message.success({content:'修改成功!',duration: 5,closable: true})
          deployList(this.env, this.appType, this.page, this.pageSize, this.searchValue).then(res => {
            res.data.results.forEach(element => {
              for (var envs in this.env_names) {
                if ( this.env_names[envs]['value'] === element['env']) {
                  element['env'] = this.env_names[envs]['label']
                }
              }
            });
            this.data1 = res.data.results
          })
        }).catch(err => {
          this.$Message.error({content:'修改失败!',duration: 5,closable: true})
        })
      },
      // 查看项目信息
      deployView (index) {
        this.$Modal.info({
          title: '查看信息',
          width: 25,
          content: `项目名称：${this.data1[index].name}<br>所属环境：${this.data1[index].env}<br>项目端口：${this.data1[index].port}<br>项目类型：${this.data1[index].application_type}<br>git地址：${this.data1[index].git_repo}<br>代码分支：${this.data1[index].branch}<br>主机记录：${this.data1[index].domain}<br>参数组：${this.data1[index].params}<br>创建日期：${this.data1[index].create_time}<br>更新日期：${this.data1[index].update_time}`
        })
      },
      // 删除
      remove (index) {
        this.$Modal.confirm({
          title: "警告!",
          content: `<p>确认删除${this.data1[index].application_type}项目${this.data1[index].name}？</p>`,
          onOk: () => {
            deleteDeploy(this.data1[index].id).then(res => {
              this.data1.splice(index, 1);
              deployList(this.env, this.appType, this.page, this.pageSize, this.searchValue).then(res => {
                res.data.results.forEach(element => {
                  for (var envs in this.env_names) {
                    if ( this.env_names[envs]['value'] === element['env']) {
                      element['env'] = this.env_names[envs]['label']
                    }
                  }
                });
                this.data1 = res.data.results
                this.count = res.data.count
                this.$Message.success({content:'删除成功!',duration: 5,closable: true})
              }).catch(err => {
                this.$Message.error('接口请求失败')
              })
            }).catch(err => {
              this.$Message.error({content:'删除失败!',duration: 5,closable: true})
            })
          },
          onCancel: () => {
            this.$Message.info('已取消删除');
          }
        })
      },
      // 获取页码并发起请求
      switchPage (page) {
        this.page = page
        deployList(this.env, this.appType, this.page, this.pageSize, this.searchValue).then(res => {
          res.data.results.forEach(element => {
            for (var envs in this.env_names) {
              if ( this.env_names[envs]['value'] === element['env']) {
                element['env'] = this.env_names[envs]['label']
              }
            }
          });
          this.data1 = res.data.results
        }).catch(err => {
          this.$Message.error('接口请求失败')
        })
      },
      // 获取选择切换的每页条数并发起请求
      switchPageSize (pageSize) {
        this.page = 1
        this.pageSize = pageSize
        deployList(this.env, this.appType, this.page, this.pageSize, this.searchValue).then(res => {
          res.data.results.forEach(element => {
            for (var envs in this.env_names) {
              if ( this.env_names[envs]['value'] === element['env']) {
                element['env'] = this.env_names[envs]['label']
              }
            }
          });
          this.data1 = res.data.results
        }).catch(err => {
          this.$Message.error('接口请求失败')
        })
      },
      // 搜索
      searchDeploy () {
        if (this.env.length!=0) {
          deployAllSearch(this.env, this.appType,this.searchValue).then(res => {
            res.data.results.forEach(element => {
              for (var envs in this.env_names) {
                if ( this.env_names[envs]['value'] === element['env']) {
                  element['env'] = this.env_names[envs]['label']
                }
              }
            });
            this.data1 = res.data.results
            this.count = res.data.count
          }).catch(err => {
            this.$Message.error('接口请求失败!')
          })
        } else {
          this.$Message.error("请选择环境!")
        }
      },
      // 此方法主要给定时刷新页面重载数据使用
      deployBuildStatus () {
        if (this.env.length!=0&&this.searchValue.length==0) {
          if(this.appType){
            deployList(this.env, this.appType, this.page, this.pageSize, this.searchValue).then(res => {
              res.data.results.forEach(element => {
                for (var envs in this.env_names) {
                  if ( this.env_names[envs]['value'] === element['env']) {
                    element['env'] = this.env_names[envs]['label']
                  }
                }
              });
              this.data1 = res.data.results
              this.count = res.data.count
            })
          }
        }
      },
      // 定时获取数据并重新加载页面
      cronGetDeployData () {
        this.cronGet = setInterval(() => this.deployBuildStatus(), 5000)
      }
    },
    mounted () {
      this.mens()
      this.cronGetDeployData()
    },
    beforeDestroy () {
      // 退出当前页面时清除此定时请求任务
      clearInterval(this.cronGet)
    }
  }
</script>
